package com.mxx.common.conv;

import org.springframework.beans.SimpleTypeConverter;

import java.time.LocalDate;
import java.time.LocalDateTime;

public class SpringConverter implements ConvertValue {

    private SimpleTypeConverter converter;

    public SpringConverter(SimpleTypeConverter converter) {
        this.converter = converter;
    }

    public static SpringConverter getInstance() {
        SimpleTypeConverter converter = new SimpleTypeConverter();
        converter.registerCustomEditor(LocalDate.class, new LocalDateEditor());
        converter.registerCustomEditor(LocalDateTime.class, new LocalDateTimeEditor());
        converter.registerCustomEditor(String.class, new StringLocalDateTimeEditor());
        return getInstance(converter);
    }

    public static SpringConverter getInstance(SimpleTypeConverter typeConverter) {
        return BeanUtil.singleton(SpringConverter.class, new Object[]{typeConverter});
    }

    public <T> T convertValue(Object sourceValue, Class<T> targetClass) {
        if (targetClass.equals(sourceValue.getClass())) {
            return (T) sourceValue;
        }
        return this.converter.convertIfNecessary(sourceValue, targetClass);
    }

}
